<template>
  <div>
    <scroller :show-scrollbar="false">
      <div v-if="step===0">
        <vm-cell label="批次">
          <text slot="title">{{params.enter_batch_no}}</text>
        </vm-cell>

        <vm-cell label="产品"
                 @cellClicked="chooseProduct">
          <text slot="title"
                :class="[!selectProduct.goods_name && 'text-muted']">{{selectProduct.goods_name || '请选择鸡苗产品'}}</text>
          <text class="icon text-muted">&#xe69b;</text>
        </vm-cell>

        <vm-cell label="日龄">
          <input slot="title"
                 type="number"
                 placeholder="请填写日龄"
                 v-model="params.day_age"
                 class="input" />
          <text class="text-muted">天</text>
        </vm-cell>

        <vm-cell label="总数">
          <input slot="title"
                 type="number"
                 placeholder="请填写进鸡苗总数"
                 v-model="params.chick_amount"
                 class="input" />
          <text class="text-muted">羽</text>
        </vm-cell>

        <vm-cell label="死亡">
          <input slot="title"
                 type="number"
                 placeholder="请填写死亡数"
                 v-model="params.die_amount"
                 class="input" />
          <text class="text-muted">羽</text>
        </vm-cell>

        <vm-cell label="淘汰">
          <input slot="title"
                 type="number"
                 placeholder="请填写淘汰数"
                 v-model="params.eli_amount"
                 class="input" />
          <text class="text-muted">羽</text>
        </vm-cell>

        <vm-cell label="均重">
          <input slot="title"
                 type="number"
                 placeholder="请填写均重"
                 v-model="params.avg_weight"
                 class="input" />
          <text class="text-muted">克</text>
        </vm-cell>

        <vm-button class="my-3"
                   :text="`${disabled ? '今天已经入栏，不能再入栏了' : '下一步'}`"
                   :disabled="disabled"
                   @buttonClicked="onNext"></vm-button>
      </div>

      <div v-else-if="step === 1">

        <div class="bg-white p-3 border-bottom">
          <text class="text-center text-lg">{{surplusAmount}}</text>
          <text class="small text-center text-muted">未入舍量(羽)</text>
        </div>

        <text class="bg-white p-3 text-muted text-center small"
              v-if="!emptyHouses.length">无空棚鸡舍</text>

        <div v-else>
          <vm-cell v-for="(house, index) in emptyHouses"
                   :key="index"
                   :label="`${house.house_no}栋入舍`">
            <input slot="title"
                   type="number"
                   :placeholder="`请填写(1~${surplusAmount})`"
                   v-model="house.inputAmount"
                   class="input"
                   @input="onInputAmount(house)" />
            <text class="text-muted">羽</text>
          </vm-cell>
        </div>

        <vm-button class="my-3"
                   text="入栏"
                   @buttonClicked="submit"></vm-button>

        <text class="p-3 text-muted small"
              @click="goPrev">上一步</text>
      </div>
    </scroller>

    <vm-mask height="600"
             width="560"
             :show-close="true"
             :show.sync="productVisible">
      <text class="p-3 border-bottom text-muted">选择产品</text>
      <text class="empty-list"
            v-if="!products.length">无产品，不能入栏</text>
      <scroller v-else
                :show-scrollbar="false">
        <div class="flex-row list-text"
             v-for="(product, index) in products"
             :key="index"
             @click="onSelectProduct(product, index)">
          <text :class="[
               'flex',
               selectProductIndex === index && 'list-text-active',
               product.disabled && 'list-text-disabled'
               ]">{{product.goods_name}}</text>
          <text class="small text-muted">库存: {{product.store_amount}}</text>
        </div>
      </scroller>
    </vm-mask>
  </div>
</template>
<script>
import VmButton from '../../components/vm-button.vue'
import VmCell from '../../components/vm-cell.vue'
import VmMask from '../../components/vm-mask.vue'
import {
  STORAGE_FARM
} from '../../plugins/constant'
import {
  CATEGORY_BABY_CHICK
} from '../../plugins/enumChick'

export default {
  components: { VmButton, VmCell, VmMask },
  props: {},
  data() {
    return {
      params: {
        enter_batch_no: '',
        product_id: '',
        day_age: '',
        die_amount: '',
        eli_amount: '',
        avg_weight: '',
        column_status: 1,
        supplier_id: '',
        enter_time: ''
      },
      products: [],
      productVisible: false,
      selectProductIndex: 0,
      step: 0,
      emptyHouses: [],
      selectProduct: {},
      disabled: true
    }
  },
  computed: {
    storeAmount() {
      return +this.selectProduct.store_amount || 0
    },
    useAmount() {
      return this.emptyHouses.reduce((total, item) => total + (+item.useAmount || 0), 0) || 0
    },
    inputAmount() {
      return this.emptyHouses.reduce((total, item) => total + (+item.inputAmount || 0), 0) || 0
    },
    surplusAmount() {
      return this.storeAmount - this.useAmount
    }
  },
  watch: {},
  created() {
    this.params.enter_batch_no = this.$utils.dateFormat(new Date(), 'yyyyMMdd')
    this.getFarm()
  },
  methods: {
    getFarm() {
      this.farm = this.$storage.getSync(STORAGE_FARM) || {}
      if (this.farm.id) {
        this.checkAreadyInToday()
        this.getProduct()
        this.getEmptyHouse()
      } else {
        this.$notice.toast({ message: '没有鸡场信息' })
        this.$router.setBackParams({ type: 1 })
      }
    },
    checkAreadyInToday() {
      // 一天只能入一次栏
      this.$api.getData({
        server: 'agr_chain',
        table: 'chick_column',
        params: {
          'enter_batch_no.eq': this.params.enter_batch_no
        },
        fields: 'enter_batch_no'
      }).then(res => {
        const data = res || []
        if (data.length) {
          this.$notice.toast({ message: '一天只能入一次栏' })
        } else {
          this.disabled = false
        }
      })
    },
    getProduct() {
      this.$api.getData({
        server: 'agr_chain',
        table: 'goods_store_view',
        params: {
          'own_org_id.eq': this.farm.id,
          'goods_category_id.endlike': CATEGORY_BABY_CHICK
        }
      }).then(res => {
        this.products = res || []
        if (this.products.length) {
          this.selectProduct = this.products[0]
          this.params.product_id = this.selectProduct.goods_id
        }
      })
    },
    getEmptyHouse() {
      this.$api.getData({
        server: 'agr_chain',
        table: 'chick_house',
        params: {
          'supplier_id.eq': this.farm.id,
          'house_status.eq': 2
        }
      }).then(res => {
        this.emptyHouses = (res || []).map(item => {
          item.useAmount = undefined
          item.inputAmount = undefined
          return item
        })
      })
    },
    chooseProduct() {
      this.productVisible = true
    },
    onSelectProduct(product, index) {
      if (product.disabled) {
        return this.$notice.toast({ message: '该产品无库存，无法入舍' })
      }
      this.selectProductIndex = index
      this.selectProduct = product
      this.params.product_id = product.goods_id
      this.productVisible = false
    },
    onNext() {
      if (!this.params.product_id) {
        return this.$notice.toast({ message: '请选择养殖产品' })
      }
      if (!this.params.day_age) {
        return this.$notice.toast({ message: '请填写日龄' })
      }
      if (this.params.die_amount === '') {
        return this.$notice.toast({ message: '请填写死亡数量' })
      }
      if (this.params.eli_amount === '') {
        return this.$notice.toast({ message: '请填写淘汰数量' })
      }
      if (!this.params.avg_weight === '') {
        return this.$notice.toast({ message: '请填写均重' })
      }
      this.step++
    },
    goPrev() {
      this.step--
    },
    onInputAmount(house) {
      const inputAmount = +house.inputAmount || 0
      if (inputAmount < 0) {
        this.$notice.toast({ message: '请输入正确的数量' })
      } else if (inputAmount === 0) {
        this.$notice.toast({ message: '数量不能为0' })
      } else if (this.storeAmount - inputAmount < 0) {
        house.inputAmount = Math.floor(inputAmount / 100)
        this.$notice.toast({ message: '超过库存量了' })
      } else {
        house.useAmount = inputAmount
      }
    },
    async submit() {
      if (this.useAmount === 0) {
        return this.$notice.toast({ message: '至少填写一个鸡舍的入舍数量' })
      }

      this.chickIn()
    },
    // 入栏
    chickIn() {
      this.params.supplier_id = this.farm.id
      this.params.enter_time = this.$utils.dateFormat(new Date())
      const masterData = { ...this.params }
      const slaveData = []
      for (const house of this.emptyHouses) {
        if (!house.useAmount) { continue }
        slaveData.push({
          chick_amount: house.useAmount,
          chick_house_id: house.chick_house_id,
          house_no: house.house_no,
          product_id: this.selectProduct.goods_id
        })
      }
      const formData = {
        masterTableInfo: JSON.stringify(masterData),
        masterTableName: 'chick_column',
        slaveTableInfo: JSON.stringify(slaveData),
        slaveTableName: 'chick_house_enter'
      }

      this.$api.relatedBatch({
        server: 'agr_chain',
        data: formData,
        errorMsg: '入栏重试，请重新入栏'
      }).then(res => {
        this.$notice.toast({ message: '入栏成功' })
        this.$router.setBackParams({ type: 1 })
        this.$router.back()
      })
    }
  }
}
</script>
<style lang="scss" scoped>
@import "../../css/variables.scss";

.icon {
  font-family: alicon;
}
.input {
  flex: 1;
  height: 60px;
  font-size: 30px;
  tint-color: #999;
}
.flex-row {
  flex-direction: row;
  align-items: center;
}
.flex {
  flex: 1;
}
.text-center {
  text-align: center;
}
.align-right {
  align-items: right;
}
.text-muted {
  color: #999;
}
.p-3 {
  padding: 30px;
}
.my-3 {
  margin-top: 30px;
  margin-bottom: 30px;
}
.border-bottom {
  border-bottom-width: 1px;
  border-bottom-color: $border-color;
}
.small {
  font-size: 26px;
}
.text-lg {
  font-size: 38px;
}
.bg-white {
  background-color: #fff;
}

.list-text {
  padding: 30px;
  border-bottom-width: 1px;
  border-bottom-color: $border-color;
}
.list-text-active {
  color: $primary;
}
.list-text-disabled {
  color: #999;
}
.empty-list {
  padding: 30px;
  font-size: 28px;
  margin-top: 50px;
  text-align: center;
}
</style>
